import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:multi_shop/models/order.dart';
import 'package:multi_shop/models/user.dart';
import 'package:multi_shop/pages/order_detail.dart';
import 'package:multi_shop/services/order_api.dart';
import 'package:multi_shop/utils/index.dart';
import 'package:multi_shop/widgets/payDialog.dart';

/// 订单状态枚举
// 订单状态: 0=待支付, 1=待发货, 2=待收货, 3=已完成, 4=售后
enum OrderStatus {
  all(-1, '全部'),
  pendingPayment(0, '待支付'),
  pendingShipment(1, '待发货'),
  pendingDelivery(2, '待收货'),
  completed(3, '已完成'),
  afterSale(4, '售后');

  final int code;
  final String label;
  const OrderStatus(this.code, this.label);

  static OrderStatus fromCode(int code) {
    return OrderStatus.values.firstWhere((e) => e.code == code);
  }

  String get text => label;
}

extension OrderStatusStyle on OrderStatus {
  Color get color {
    switch (this) {
      case OrderStatus.pendingPayment: // 待支付
        return Colors.orange;
      case OrderStatus.pendingShipment: // 待发货
        return Colors.blue;
      case OrderStatus.pendingDelivery: // 待收货
        return Colors.teal;
      case OrderStatus.completed: // 已完成
        return Colors.green;
      case OrderStatus.afterSale: // 售后
        return Colors.red;
      case OrderStatus.all: // 全部（一般不单独显示）
      default:
        return Colors.black87;
    }
  }
}

/// 订单列表页面，Tab 切换不同状态，展示商品图片、名称、单价、数量，并支持“确认收货”按钮
class OrderListPage extends StatefulWidget {
  const OrderListPage({super.key});

  @override
  State<OrderListPage> createState() => _OrderListPageState();
}

class _OrderListPageState extends State<OrderListPage>
    with SingleTickerProviderStateMixin {
  List<MallOrder> orders = [];
  final OrderApi _api = OrderApi();
  final List<int> statusOfTab = const [-1, 0, 1, 2, 3, 4];
  int _currentIndex = 0;
  final List<Tab> tabs = [...OrderStatus.values.map((e) => Tab(text: e.text))];
  TabController? tabController;
  UserInfo? userInfo;
  @override
  void initState() {
    super.initState();
    _getOrderList(-1);
    userInfo = GetStorage().read('userInfo');
    debugPrint('userInfo: ${jsonEncode(userInfo)}');
    tabController = TabController(vsync: this, length: tabs.length);
    tabController?.addListener(() {
      if (!tabController!.indexIsChanging &&
          tabController!.index != _currentIndex) {
        _currentIndex = tabController!.index;
        final status = statusOfTab[_currentIndex];
        _getOrderList(status);
      }
    });
  }

  // 获取订单列表
  Future<void> _getOrderList(int status) async {
    List<MallOrder> data = await _api.list(status: status);
    setState(() {
      orders = data;
    });
  }

  String _formatDate(String dt) {
    final date = DateTime.parse(dt); // 先解析字符串
    final m = date.month.toString().padLeft(2, '0');
    final d = date.day.toString().padLeft(2, '0');
    final h = date.hour.toString().padLeft(2, '0');
    final min = date.minute.toString().padLeft(2, '0');
    final s = date.second.toString().padLeft(2, '0');
    return '${date.year}-$m-$d $h:$min:$s';
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: tabs.length,
      child: Scaffold(
        appBar: AppBar(
          title: Text('我的订单'),
          bottom: TabBar(
            controller: tabController,
            tabAlignment: TabAlignment.start,
            isScrollable: true,
            tabs: tabs,
          ),
        ),
        body: TabBarView(
          controller: tabController,
          children: OrderStatus.values.map((status) {
            if (orders.isEmpty) {
              return const Center(child: Text('暂无订单'));
            }
            return ListView.separated(
              itemCount: orders.length,
              separatorBuilder: (_, __) => Divider(height: 1),
              itemBuilder: (_, idx) {
                final order = orders[idx];
                return Card(
                  color: Colors.grey[50],
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                  margin: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  child: Padding(
                    padding: EdgeInsets.all(12),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        GestureDetector(
                          onTap: () => {
                            Get.to(OrderDetailPage(orderNo: order.orderNo)),
                          },
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Column(
                                    children: [
                                      Text(
                                        '订单号: ${order.orderNo}',
                                        style: TextStyle(
                                          fontSize: 14,
                                          color: Colors.grey[600],
                                        ),
                                      ),
                                      SizedBox(height: 4),
                                      Text(
                                        "下单时间：${_formatDate(order.createdAt)}",
                                        style: TextStyle(
                                          fontSize: 12,
                                          color: Colors.grey[500],
                                        ),
                                      ),
                                    ],
                                  ),
                                  // 订单状态
                                  SizedBox(width: 8),
                                  Text(
                                    order.status.text,
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500,
                                      color: order.status.color, // 调用扩展属性
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(height: 8),
                              Column(
                                children: (order.items ?? [])
                                    .map<Widget>(
                                      (e) => Padding(
                                        padding: const EdgeInsets.symmetric(
                                          vertical: 4,
                                        ),
                                        child: Row(
                                          children: [
                                            ClipRRect(
                                              borderRadius:
                                                  BorderRadius.circular(4),
                                              child: Image.network(
                                                e.imageUrl,
                                                width: 60,
                                                height: 60,
                                                fit: BoxFit.cover,
                                                loadingBuilder:
                                                    (context, child, progress) {
                                                      if (progress == null) {
                                                        return child;
                                                      }
                                                      return Container(
                                                        width: 60,
                                                        height: 60,
                                                        color: Colors.grey[200],
                                                        child: Center(
                                                          child: SizedBox(
                                                            width: 20,
                                                            height: 20,
                                                            child:
                                                                CircularProgressIndicator(
                                                                  strokeWidth:
                                                                      2,
                                                                ),
                                                          ),
                                                        ),
                                                      );
                                                    },
                                                errorBuilder:
                                                    (
                                                      context,
                                                      error,
                                                      stackTrace,
                                                    ) {
                                                      return Container(
                                                        width: 60,
                                                        height: 60,
                                                        color: Colors.grey[200],
                                                        child: Center(
                                                          child: Icon(
                                                            Icons.broken_image,
                                                            color: Colors.grey,
                                                          ),
                                                        ),
                                                      );
                                                    },
                                              ),
                                            ),
                                            SizedBox(width: 12),
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    e.name,
                                                    maxLines: 1,
                                                    overflow:
                                                        TextOverflow.ellipsis,
                                                    style: TextStyle(
                                                      fontSize: 16,
                                                      fontWeight:
                                                          FontWeight.bold,
                                                    ),
                                                  ),
                                                  SizedBox(height: 4),
                                                  Row(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment
                                                            .spaceBetween,
                                                    children: [
                                                      Row(
                                                        children: [
                                                          Text(
                                                            '¥',
                                                            style: TextStyle(
                                                              fontSize: 12,
                                                              color: Colors.red,
                                                            ),
                                                          ),
                                                          SizedBox(width: 2),
                                                          Text(
                                                            e.price
                                                                .toStringAsFixed(
                                                                  2,
                                                                ),
                                                            style: TextStyle(
                                                              fontWeight:
                                                                  FontWeight
                                                                      .bold,
                                                              color: Colors.red,
                                                            ),
                                                          ),
                                                        ],
                                                      ),
                                                      Text(
                                                        'x${e.quantity}',
                                                        style: TextStyle(
                                                          color:
                                                              const Color.fromARGB(
                                                                255,
                                                                128,
                                                                128,
                                                                128,
                                                              ),
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    )
                                    .toList(),
                              ),
                              SizedBox(height: 8),
                              Visibility(
                                visible: order.status != OrderStatus.completed,
                                child: Divider(
                                  height: 1,
                                  thickness: 1,
                                  color: Colors.grey[300],
                                ),
                              ),
                              SizedBox(height: 8),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  switch (order.status) {
                                    OrderStatus.pendingDelivery =>
                                      ElevatedButton(
                                        onPressed: () {
                                          // TODO: 确认收货逻辑
                                          toastCenter('确认收货成功');
                                        },
                                        child: const Text('确认收货'),
                                      ),
                                    OrderStatus.pendingPayment =>
                                      ElevatedButton(
                                        onPressed: () {
                                          if (userInfo!.hasPayPwd == false) {
                                            showDialog(
                                              context: context,
                                              builder: (_) => AlertDialog(
                                                title: Text('提示'),
                                                content: Text('请先设置支付密码'),
                                                actions: [
                                                  TextButton(
                                                    onPressed: () {
                                                      Navigator.of(
                                                        context,
                                                      ).pop(); // 关闭 AlertDialog
                                                      Get.toNamed('/set_pin');
                                                    },
                                                    child: Text('去设置'),
                                                  ),
                                                ],
                                              ),
                                            );
                                          } else {
                                            showDialog(
                                              context: context,
                                              builder: (_) => PayDialog(
                                                orderNo: order.orderNo,
                                                amount: order.totalAmount,
                                                balance: userInfo!.balance,
                                                onConfirm: (method, pwd) {
                                                  debugPrint(
                                                    '选择的支付方式：${method.label}',
                                                  );
                                                  debugPrint('输入的支付密码：$pwd');
                                                  // TODO: 调用支付接口
                                                },
                                              ),
                                            );
                                          }
                                        },
                                        child: const Text('去支付'),
                                      ),
                                    OrderStatus.pendingShipment =>
                                      ElevatedButton(
                                        onPressed: () {
                                          toastCenter('提醒发货成功');
                                        },
                                        child: const Text('提醒发货'),
                                      ),
                                    // OrderStatus.completed => const Text(
                                    //   '已完成',
                                    //   style: TextStyle(color: Colors.green),
                                    // ),
                                    OrderStatus.afterSale => ElevatedButton(
                                      onPressed: () {
                                        toastCenter('取消售后成功');
                                      },
                                      child: const Text('取消售后'),
                                    ),
                                    _ => const SizedBox.shrink(), // 其他状态不显示
                                  },
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              },
            );
          }).toList(),
        ),
      ),
    );
  }
}
